<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建通知公告' : "编辑通知公告" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="动态名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入动态名称"></el-input>
        </el-form-item>

        <el-form-item label="动态关键词" prop="keyword">
          <el-input v-model="ruleForm.keyword" placeholder="请输入动态关键词"></el-input>
        </el-form-item>

        <el-form-item label="动态类别" prop="newsType">
          <el-select v-model="ruleForm.newsType" placeholder="请选择动态类别" disabled>
            <el-option label="本地填报" value="本地填报" />
            <el-option label="网络采集" value="网络采集" />
          </el-select>
        </el-form-item>

        <el-form-item label="发布单位" prop="pubUnit">
          <el-input v-model="ruleForm.pubUnit" placeholder="请输入发布单位"></el-input>
        </el-form-item>

        <el-form-item label="发布日期" prop="pubDate">
          <el-date-picker
            v-model="ruleForm.pubDate"
            type="date"
            placeholder="请选择发布日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="ruleForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>

        <el-form-item label="正文内容" prop="content">
          <t-editor v-model="ruleForm.content" @input="inputContent" style="width: 100%;"/>
        </el-form-item>

        <el-form-item label="封面图片" prop="newsPicture">
          <el-image style="width: 313px;"
            :src="imageUrl ? imageUrl : ''" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-image style="width: 313px;" src="/images/course_default.png" fit="cover" />
              </div>
            </template>
          </el-image>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传封面图片
          </el-button>
          <span style="margin-left: 10px;">请上传不超过10M的图片，格式：jpg/png/jpeg</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCollectAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled, Picture } from '@element-plus/icons-vue'
import tEditor from "@/components/tinymceEditor/tEditor.vue"
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { format } from '@/plugins/moment.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getCollectDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getCollectDetail = () => {
  loading.value = true
  http.$GET("/PreachM/GetPreachNewsDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return
    
    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理发布日期 */
    ruleForm.value.pubDate = format(res.result.pubDate)

    /* 动态类别 */
    if(res.result.newsType == '' || !res.result.newsType){
      ruleForm.value.newsType = '本地填报'
    }

    /* 动态封面图片路径 */
    if(!isJsonString(res.result.newsPicture)){
      imageUrl.value = ""
      ruleForm.value.newsPicture = ""
      return
    }
    if(res.result.newsPicture != ''){
      let picture = JSON.parse(res.result.newsPicture)

      if(picture.filePathArray){
        imageUrl.value = import.meta.env.VITE_APP_STATIC_URL + picture.filePathArray[0].CompleteFilePath
      }else{
        imageUrl.value = ""
        ruleForm.value.newsPicture = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 日期禁选范围 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: "",
  name: "",
  keyword: "",
  newsType: "本地填报",
  pubUnit: "",
  pubDate: "",
  author: "",
  content: "",
  newsPicture: "",
})

/* 封面图片路径 */
const imageUrl = ref(null)
/* 是否有上传图片 */
const isUploadImage = ref(false)

/* 上传文件校验 */
const checkFile = (rule, value, callback) => {
  if (!ruleForm.value.newsPicture) {
    callback(new Error('请上传附件'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请填写动态名称', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  keyword: [
    { required: true, message: '请填写动态关键词', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  newsType: [
    { required: true, message: '请选择动态类别', trigger: 'blur' }
  ],
  pubUnit: [
    { required: true, message: '请填写发布单位', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  pubDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请填写作者', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  content: [
    { required: true, message: '请填写正文内容', trigger: 'blur' }
  ],
  /* newsPicture: [
    { required: true, validator: checkFile, message: '请上传附件', trigger: 'change' }
  ], */
})

/* 富文本内容变化 */
const inputContent = (newVal) => {
  if(newVal){
    ruleFormRef.value.clearValidate('content')
  }
  ruleForm.value.content = newVal
}

/* 点击上传文件 */
const uploadEvent = () => {

  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG)$/)){
      ruleForm.value.newsPicture = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }
    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.newsPicture = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadImage.value = true
      ruleForm.value.newsPicture = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('newsPicture')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if(!isUploadImage.value) {
        delete ruleForm.value.newsPicture
      }

      http.$POST("/PreachM/AddOrUpdatePreachNews", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');
          route.push({
            path: "/backend/publicize-collect"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ""
  isUploadImage.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/publicize-collect",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>